package com.andyliu.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class VelocityGenerator {
    protected VelocityEngine ve;

    /**
     * 准备velocity引擎
     */
    public void init() {
        ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
    }

    /**
     * @throws IOException
     */
    public void buildFileByTemplate(String outputPath, String filePath,String templatePath,VelocityContext ctx) throws IOException {
        //添加数据
        //取得模板文件
        Template domainModelTemplateA = ve.getTemplate(templatePath, "utf-8");
        //渲染并保存文件
        render(domainModelTemplateA, ctx, outputPath);
    }


    /**
     * 渲染
     *
     * @param template
     * @param ctx
     * @param file
     */
    protected void render(Template template, VelocityContext ctx, String file) {
        File out = new File(file);
        FileWriter writer = null;
        try {
            //如果路径不存在，创建路径
            out.getParentFile().mkdirs();
            writer = new FileWriter(out);
            //渲染
            template.merge(ctx, writer);
            writer.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//    public static void main(String[] args) throws IOException {
//        VelocityGenerator velocityGenerator = new VelocityGenerator();
//        velocityGenerator.init();
//        velocityGenerator.buildFileByTemplate("sdfsdf", "a.html", "/Users/apple/Documents/ideaworkspace/boot-manager/src/main/");
//    }


}